package com.wang.cloud.manage.service.manage;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.wang.cloud.common.core.exception.ServiceException;
import com.wang.cloud.manage.convert.PlatformUserConvertor;
import com.wang.cloud.manage.domain.co.*;
import com.wang.cloud.manage.domain.entity.PlatformUserEntity;
import com.wang.cloud.manage.domain.vo.*;
import com.wang.cloud.manage.enums.PlatformEnum;
import com.wang.cloud.manage.service.IPlatformUserService;
import com.wang.cloud.manage.service.IUserRoleRelationService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author wang ye
 * @date 2024/7/16
 */
@Slf4j
@Service
public class SysUserManage {
    private static final String PLATFORM_ID = PlatformEnum.SYS_MANAGE.getPlatformId();

    @Resource
    private IPlatformUserService platformUserService;
    @Resource
    private PlatformUserConvertor convertor;
    @Resource
    private BCryptPasswordEncoder bCryptPasswordEncoder;
    @Resource
    private SysUserRoleManage roleManage;
    @Resource
    private IUserRoleRelationService userRoleRelationService;

    public IPage<SysUserPageVo> page(PlatformUserPageCo pageCo) {
        pageCo.setPlatformId(PLATFORM_ID);
        IPage<SysUserPageVo> pageVO = platformUserService.sysPage(pageCo);
        fillUserRoles(pageVO);
        return pageVO;
    }

    private void fillUserRoles(IPage<SysUserPageVo> pageVO) {
        List<SysUserPageVo> records = pageVO.getRecords();
        if (records.isEmpty()) {
            return;
        }
        List<Long> ids = records
                .stream()
                .map(SysUserPageVo::getId)
                .collect(Collectors.toList());
        Map<Long, List<UserRoleNameVo>> map = userRoleRelationService.queryRoleByUserIds(ids);

        records.forEach(vo -> {
            vo.setRoleList(map.getOrDefault(vo.getId(), Collections.emptyList()));
        });
    }

    public SysUserDetailVo detailInfo(Long id) {
        PlatformUserEntity entity = getAndCheckId(id);
        List<RoleNameVo> roles = roleManage.queryRoleNamesByUserId(id);
        SysUserDetailVo userVo = convertor.entityToSysDetailVo(entity, roles);
        return userVo;
    }


    @Transactional(rollbackFor = Exception.class)
    public Long addSysUser(SysUserAddCo addCo) {
        PlatformUserEntity entity = platformUserService.getUserByPhone(PLATFORM_ID, addCo.getPhone());
        if (Objects.nonNull(entity)) {
            throw new ServiceException("该手机号已存在");
        }
        entity = convertor.addCoToEntity(addCo);
        entity.setPlatformId(PLATFORM_ID);
        entity.setUserName(addCo.getPhone());
        entity.setPassword(bCryptPasswordEncoder.encode(addCo.getPassword()));
        // 新增用户
        platformUserService.save(entity);
        roleManage.updateUserRole(entity.getId(), addCo.getRoleIds());
        return entity.getId();
    }

    @Transactional(rollbackFor = Exception.class)
    public Long updateSysUser(SysUserUpdateCo updateCo) {
        getAndCheckId(updateCo.getId());
        PlatformUserEntity entity = convertor.updateCoToEntity(updateCo);
        // 新增用户
        platformUserService.updateById(entity);
        roleManage.updateUserRole(entity.getId(), updateCo.getRoleIds());
        return entity.getId();
    }

    @Transactional(rollbackFor = Exception.class)
    public Boolean updateSysUserStatus(UpdateStatusCo co) {
        getAndCheckId(co.getId());
        PlatformUserEntity entity = new PlatformUserEntity();
        entity.setId(co.getId());
        entity.setStatus(co.getStatus());
        return platformUserService.updateById(entity);
    }

    @Transactional(rollbackFor = Exception.class)
    public Boolean restSysUserPwd(SysUserRestPwdCo co) {
        getAndCheckId(co.getId());
        PlatformUserEntity entity = new PlatformUserEntity();
        entity.setId(co.getId());
        entity.setPassword(bCryptPasswordEncoder.encode(co.getPassword()));
        return platformUserService.updateById(entity);
    }

    public void delSysUser(Long id) {
        PlatformUserVo oldEntity = platformUserService.getInfo(PLATFORM_ID, id);
        if (Objects.isNull(oldEntity)) {
            return;
        }
        // 删除账号
        platformUserService.removeById(id);
        // TODO 删除-账号角色
    }

    private PlatformUserEntity getAndCheckId(Long id) {
        PlatformUserEntity oldInfo = platformUserService.getUserById(PLATFORM_ID, id);
        if (Objects.isNull(oldInfo)) {
            throw new ServiceException("账号不存在或已删除");
        }
        return oldInfo;
    }
}
